<?php
/**
 * 作者: 王志昂-黑米<wangzhiangtony@qq.com>
 * 个人说明: 春水初涨，春林初盛，春风十里，不如你。
 * 创建时间: 2016-01-21 21:28
 * 说明:
 */

namespace Home\Controller;

use Think\Controller;
use Think\Log;

class GitController extends Controller
{
    public function index()
    {
        Log::init(array(
            'log_path' => C('LOG_PATH')
        ));
        $requestBody = file_get_contents('php://input');
        if (empty($requestBody)) {
            echo '发送失败';
            return false;
        }
        $content = json_decode($requestBody, true);

        $message = "";
        // 获取所有的订阅信息
        $sql = "SELECT
                d.realname as subscriber,
                b.project_name,
                b.git_url,
                c.realname
            FROM
                zt_code_subscribe_git AS a
            LEFT JOIN zt_code_git_project AS b ON a.git_project_id = b.id
            LEFT JOIN zt_user AS c ON a.user_id_subscribe_to = c.id
            LEFT JOIN zt_user AS d ON a.user_id_subscriber = d.id
            WHERE
                c.realname = '" . $content['user_name'] . "'
            AND b.project_name = '" . $content['repository']['name'] . "'
            AND a.is_deleted = 'N'";
        $res = M()->query($sql);

        // 获取组织的人员
        $deptUserList = D('Dingding', 'Service')->getTechUserList();
        $newDeptUserList = array();
        foreach ($deptUserList as $deptUser) {
            $newDeptUserList[$deptUser['name']] = $deptUser['userid'];
        }

        Log::write('用户：' . $content['user_name']);
        Log::write('项目：' . $content['repository']['name']);
        // 发送给订阅者
        foreach ($res as $value) {
            if (isset($newDeptUserList[$value['subscriber']])) {
                if ($content['total_commits_count'] > 0) {
                    $message .= $content['user_name'] . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . $content['total_commits_count'] . '个commit：' . "\n";
                    $count = 0;
                    foreach ($content['commits'] as $commit) {
                        $count++;
                        $message .= $count . '. ' . $commit['author']['name'] . '在' . date('Y年m月d日 h:i:s', strtotime($commit['timestamp'])) . ' 提交的：' . $commit['message'] . "\n";
                        $message .= '点击 ' . $commit['url'] . ' 查看本次commit diff' . "\n";
                    }
                    echo $message;
                    Log::write($message);
                } else {
                    $message .= $content['user_name'] . '在' . $content['repository']['name'] . '项目创建或者删除了一个分支:' . $content['ref'] . "\n";
                }
                echo D('Dingding', 'Service')->sendTextMsg($newDeptUserList[$value['subscriber']], $message);
            }
        }
    }
}